package com.buka.goods.Listener;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.buka.goods.config.RabbitMqConfig;
import com.buka.goods.service.ProductDetailsService;
import com.buka.pojo.Order;
import com.buka.pojo.Task;
import com.buka.server.pojo.ProductDetails;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;


@Component
public class GoodsListener {
    @Autowired
    private ProductDetailsService productDetailsService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RedisTemplate redisTemplate;

    @RabbitListener(queues = RabbitMqConfig.GOODS_QUEUE)
    public void main1(Task task) {

        //6 判断redis中是否存在任务
        Object o = redisTemplate.opsForValue().get(task.getId());
        if (o != null) {
            return;
        }

        //7 任务添加到redis中
        redisTemplate.opsForValue().set(task.getId(), task, 30, TimeUnit.MINUTES);

        //减库存
        String requestBody = task.getRequestBody();
        Order order = JSONObject.parseObject(requestBody, Order.class);
        boolean b = productDetailsService.reducedInventory(order.getProductId(), order.getNum());

        if (b) {//判断减库存是否成功
            //跳转支付
            rabbitTemplate.convertAndSend("", RabbitMqConfig.ALIPAY_QUEUE, order);
            System.out.println("zhifu111");
        } else {
            //失败 查询库存
            ProductDetails productDetails = productDetailsService.findList(order.getProductId()).get(0);
            if (productDetails != null && productDetails.getNum() >= order.getNum()) {
                //库存充足 重试

                throw new RuntimeException();
            } else {
                //库存不足 回滚(给mq发消息 订单服务关闭订单（改状态）)
                rabbitTemplate.convertAndSend("", RabbitMqConfig.ORDER_QUEUE, order);
            }
        }
        //删除消息表中的数据（给mq发消息删除消息数据）
        rabbitTemplate.convertAndSend("", RabbitMqConfig.TASK_QUEUE, task);
    }

    @RabbitListener(queues = RabbitMqConfig.ADD_INVENTORY_QUEUE)
    public void rollback(Order order){
        productDetailsService.addInventory(order.getProductId(), order.getNum());
    }

}
